﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Common.Core
{
	public static class ListHelper
	{
		public static void Synchronize( IList source, IList target )
		{
			ListDifferencer differencer = new ListDifferencer( source.Cast<object>(), target.Cast<object>() );
			List<object> 
				add = differencer.GetLeftDifference(),
				remove = differencer.GetRightDifference();

			// Remove old items:
			remove.ForEach( item => target.Remove( item ) );

			// Add new items:
			add.ForEach( item => target.Add( item ) );
		}

		public static Type ResolveElementType( Type type )
		{
			if ( !type.HasElementType )
			{
				PropertyInfo info = type.GetProperty( "Item", CommonBindingFlags.AllProperties );
				Type result = info != null ? info.PropertyType : ResolveListItemType( type );
				return result;
			}
			return type.GetElementType();
		}

		static Type ResolveListItemType( Type type )
		{
			if ( type.IsGenericType && typeof(IEnumerable<>).IsAssignableFrom( type.GetGenericTypeDefinition() ) )
			{
				Type[] arguments = type.GetGenericArguments();
				return arguments.Length == 1 ? arguments[0] : null;
			}
			return null;
		}
	}
}
